<?php

namespace Biz\model\store;

use Doraemon\pockets\datebase\BaseDbModel;
use Medoo\Medoo;

class StoreAskLike extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db_store';

    const _CONFIG_SELECT_ = 'db_store';

    const _DATABASE_ = 'store';

    const _TABLE_NAME = 'store_ask_like';

    const STATUS_NORMAL = 1;//点赞
    const STATUS_CANCEL = 0;//取消点赞

    public static function getListByWhere($where, $field = '*')
    {
        $where['like_status'] = self::STATUS_NORMAL;
        return self::select($field, $where);
    }

    public static function add($data)
    {
        if (!isset($data['addtime'])) {
            $data['addtime'] = date('Y-m-d H:i:s');
        }
        if (!isset($data['edittime'])) {
            $data['edittime'] = date('Y-m-d H:i:s');
        }
        $result = self::insert($data)->rowCount();
        if ($result) {
            return self::id();
        }

        return false;
    }

    public static function updateData($data, $where)
    {
        if (!isset($data['edittime'])) {
            $data['edittime'] = date('Y-m-d H:i:s');
        }
        $ret = self::update($data, $where);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return true;
    }

    public static function getInfoById($id)
    {
        return self::get('*', ['id' => $id]);
    }

    public static function getUserLikeInfo($uid, $answerId)
    {
        return self::get('*', ['uid' => $uid, 'answer_id' => $answerId]);
    }

    public static function getCount($where)
    {
        $where['like_status'] = self::STATUS_NORMAL;
        return self::count($where);
    }

    public static function getAnswerLikeCount(array $answerIds)
    {
        $result = [];
        $where = [
            'answer_id' => $answerIds,
            'like_status' => self::STATUS_NORMAL,
            'GROUP' => ['answer_id']
        ];
        $res = self::select(['count' => Medoo::raw("count(id)"), 'ask_id', 'answer_id'], $where);
        $list = array_column($res, null, 'answer_id');
        foreach ($answerIds as $answerId) {
            if (isset($list[$answerId])) {
                $result[$answerId] = $list[$answerId]['count'];
            } else {
                $result[$answerId] = 0;
            }
        }
        return $result;
    }


}